#include "googleplugin.h"

GooglePlugin::GooglePlugin(){
    QString seed = this->toString();
    ID = QCryptographicHash::hash( seed.toAscii(), QCryptographicHash::Md5);

    downloader = new Downloader(this);
    checked = true;

    connect(downloader, SIGNAL(errorOccured(const QString &)),
            this, SLOT(catchError(const QString&)));

    //>>>>>>>>
    //! connecting the downloader.done() signal to member slot finished()
    connect(downloader, SIGNAL(done(const QStringList&)),
            this, SLOT(finished(const QStringList&)));
    //<<<<<<<<

    searchKey=QString("q");
    url.setHost("www.google.com");
    url.setPath("/dictionary");





    QStringList queryLang( QStringList()
                          <<"en|fr"<<"fr|en" /*<<"fr|fr"*/ <<"en|de"<<"de|en"//<<"de|de"
                          <<"en|it"<<"it|en"//<<"it|it"
                          <<"en|ko"<<"ko|en"<<"en|es"<<"es|en"/*<<"es|es"*/<<"en|ru"<<"ru|en"//<<"ru|ru"
                          <<"en|zh-TW"<<"zh-TW|en"/*<<"zh-TW|zh-TW"*/<<"en|zh-CN"<<"zh-CN|en"//<<"zh-CN|zh-CN"
                          <<"en|pt"<<"pt|en"/*<<"pt|pt"<<"en|hi"<<"hi|en"<<"nl|nl"*/<<"en|ar"<<"ar|en"
                          <<"en|cs"<<"cs|en"<<"en|th"<<"th|en"<<"en|bg"<<"bg|en"<<"en|hr"<<"hr|en"
                          <<"en|fi"<<"fi|en"<<"en|iw"<<"en|el"<<"el|en"<<"en|sr"<<"sr|en"//<<"en|en"
                         );

    LangPairList lplst = ( LangPairList()
                           << qMakePair(ENG, FRA) << qMakePair(FRA, ENG)
                           //<< qMakePair(FRA, FRA)
                           << qMakePair(ENG, GER)
                           << qMakePair(GER, ENG) //<< qMakePair(GER, GER)
                           << qMakePair(ENG, ITA) << qMakePair(ITA, ENG)
                           //<< qMakePair(ITA, ITA)
                           << qMakePair(ENG, KOR)
                           << qMakePair(KOR, ENG) << qMakePair(ENG, ESP)
                           << qMakePair(ESP, ENG) //<< qMakePair(ESP, ESP)
                           << qMakePair(ENG, RUS) << qMakePair(RUS, ENG)
                           //<< qMakePair(RUS, RUS)
                           << qMakePair(ENG, ZHTW)
                           << qMakePair(ZHTW, ENG) //<< qMakePair(ZHTW,ZHTW)
                           << qMakePair(ENG, ZHCN) << qMakePair(ZHCN,ENG)
                           //<< qMakePair(ZHCN, ZHCN)
                           << qMakePair(ENG, POR)
                           << qMakePair(POR, ENG)
                           //<< qMakePair(POR,POR)
                           //<< qMakePair(ENG, HIN) << qMakePair(HIN, ENG)
                           //<< qMakePair(NED, NED)
                           << qMakePair(ENG, ARA)
                           << qMakePair(ARA, ENG) << qMakePair(ENG, CZH)
                           << qMakePair(CZH, ENG) << qMakePair(ENG, THI)
                           << qMakePair(THI, ENG) << qMakePair(ENG, BGR)
                           << qMakePair(BGR, ENG) << qMakePair(ENG, HRV)
                           << qMakePair(HRV, ENG) << qMakePair(ENG, FIN)
                           << qMakePair(FIN, ENG) << qMakePair(ENG, HEB)
                           << qMakePair(ENG, GRE) << qMakePair(GRE, ENG)
                           << qMakePair(ENG, SER) << qMakePair(SER, ENG)
                           //<< qMakePair(ENG, ENG)
                           );
    int i=0;
    foreach( LangPair pair, lplst ) {
        //!populating LangHash
        supportedLangs[pair] = lngConv.lang2Str(pair.first) +"-"+ lngConv.lang2Str(pair.second);

        StrPairList lst;
        lst << StringPair( "langpair" , queryLang[i] );
        query.insert( pair, lst );
        ++i;
    }

}


bool GooglePlugin::search(const State &s) {
    if (query.contains(s.dict)) {
        if ( s.dict.first == s.dict.second ) singleMode=true;
        else singleMode=false;

        StrPairList actQuery = query[s.dict];
        actQuery.append( qMakePair( searchKey, s.word ) );
        qDebug() <<"ACTQUERY: "<< actQuery;

        url.setQueryItems(actQuery);
        url.setScheme("http");
        qDebug()<<"DICTIONARIES_URL: "<<url.toString();

        downloader->setUrl(url);
        downloader->download();

        return true;

    } else {
        return false;
    }
}

void GooglePlugin::finished(const QStringList &lst ) {
    qDebug() << "In function "+QString(Q_FUNC_INFO);


    QList< QRegExp > rxlist;
    QRegExp nl("\n");
    QRegExp strong("<strong>");
    QRegExp endstrong("</strong>");
    QRegExp andnbsp(",&nbsp");
    QRegExp remdfn("</dfn>\\s");
    QRegExp dfn("\\s<dfn>\\s");
    QRegExp desc("<span\\sclass=\"desc\">");

    //*	A QRegExp list is used, to remove unneeded junk from result
    //* << QRegExp("(^.+)<!--result-->") << QRegExp("<!--/result-->(.+$)")

    rxlist << nl <<strong << endstrong <<andnbsp<<remdfn;

    //*	&lst is a QStringList of downloaded html sites, but we only downloaded one site, so we need lst.first()
    QString result = utils::remove( lst.first(), rxlist);

    result = result.replace(dfn, ";");
    result = result.remove(desc);
    result = result.replace("《", "(");
    result = result.replace("》", ")");
    result = result.replace("</span> ;", ";");

    QFile file("google.txt", this);;
    file.open(QIODevice::WriteOnly);
    QTextStream out(&file);
    out<<result;
    file.close();

    QRegExp first("<h2\\sclass=\"wd\">\\s([^<>/\"]+)\\s<span");
    QRegExp second;
    if (singleMode){
        second.setPattern("<span\\sclass=\"phn\">\\s([^<>/\"]+)\\s</span");
    }else second.setPattern("class=\"mn\">\\s([^<>/\"]+)(</span>)?\\s</?span");
    first.setMinimal(true);
    second.setMinimal(true);

    Parser parser( result, first, second );
    hash=parser.parse("1");
    first.setPattern("<li>\\s([^<>/\"]+)(</span>)?\\s<br>;");
    second.setPattern("<br>;([^<>/\"]+)\\s</");
    parser.setRegExp(first,second);
    hash.add(parser.parse(";"));
    qDebug("hash.debug()>>>>");
    hash.debug();
    qDebug("<<<<hash.debug()");

    //if ( !pairList.isEmpty() && pairList.last().second.split(" ").first() == "=>" ) pairList.removeLast(); // remove junk

    emit done( hash, url.host() );
}

const LangHash GooglePlugin::getLangHash() const{
    return supportedLangs;
}

bool GooglePlugin::isChecked(){
    return checked;
}

QString GooglePlugin::description(){
    QStringList values=supportedLangs.values();
    values.sort();
    return values.join(", ")+"\n"+tr("Szleng kifejezések szó utáni [sl.] jelzéssel kereshetők.");
}

void GooglePlugin::setChecked(bool opt){
    checked = opt;
}

void GooglePlugin::catchError(const QString &msg ){
    emit errorOccured( msg );
}



Q_EXPORT_PLUGIN2(googleplugin, GooglePlugin)
